package net.ojbk.sso.center.web.exceptionResolver;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/4/9
 * Time: 16:52
 * Description: No Description
 */
public class CenterExceptionResolver implements HandlerExceptionResolver {
    private static Logger logger = Logger.getLogger(CenterExceptionResolver.class);

    /**
     * Try to resolve the given exception that got thrown during handler execution,
     * returning a {@link ModelAndView} that represents a specific error page if appropriate.
     * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty}
     * to indicate that the exception has been resolved successfully but that no view
     * should be rendered, for instance by setting a status code.
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  the executed handler, or {@code null} if none chosen at the
     *                 time of the exception (for example, if multipart resolution failed)
     * @param ex       the exception that got thrown during handler execution
     * @return a corresponding {@code ModelAndView} to forward to, or {@code null}
     * for default processing
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv = new ModelAndView();
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("msg", ex.getMessage());

        FastJsonJsonView view = new FastJsonJsonView();
        view.setAttributesMap(attributes);
        mv.setView(view);
        mv.setStatus(HttpStatus.BAD_REQUEST);
        logger.debug("异常：" + ex.getMessage(), ex);
        return mv;
    }
}
